import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;
    public TcpEchoClient(String serverIP, int serverPort) throws IOException {
        //连接服务器
        socket = new Socket(serverIP, serverPort);
    }
    public void start(){
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            Scanner scannerIn = new Scanner(System.in);
            System.out.println("客户端启动");
            while(true){
                System.out.println("->");
                //1. 从控制台获取请求
                String request = scannerIn.nextLine();
                //2. 给服务器发送请求
                printWriter.println(request);
                printWriter.flush();
                //3. 接收响应
                if(!scanner.hasNextLine()){
                    break;
                }
                String response = scanner.nextLine();
                //4. 打印响应结果
                System.out.println(request);
            }
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
//        TcpEchoClient client = new TcpEchoClient("127.0.0.1", 9090);
        TcpEchoClient client = new TcpEchoClient("118.31.188.7", 9090);
        client.start();
    }
}
